package com.example.fishdriver.recyclerviewdemo.srcollcompletelister;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.os.Handler;
import android.support.v4.view.MotionEventCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.OverScroller;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.fishdriver.recyclerviewdemo.R;

import java.util.Date;


/**
 * 写一个检测子view到底后的消耗事件
 */
public class BottomPullView extends LinearLayout {
    //默认无用的pointer标记
    private static final int INVALID_POINTER = -1;
    //获取屏幕宽高
    private final int screenWidth;
    private final int screenHeight;

    private View mTagerView;
    private Context mContext;

    private OverScroller mScroller;

    private float mInitialDownY;
    private float mInitialMotionY;
    private boolean mIsBeingDragged;
    private float mTouchSlop;
    private int mActivePointerId = INVALID_POINTER;

    private LinearLayout footView;
    private TextView refreshStatusTextView;
    private ProgressBar listviewHheaderProgressbar;
    private ImageView listviewHeaderArrow;
    private TextView tvLastRefreshTime;
    private TextView tvUpdataTimeTtip;

    private String lastRefreshTimeStr;
    //footView宽高
    private int mFootViewWidth;
    private int mFootViewHeight;
    private boolean isLoadData;
    private long lasttime;


    public BottomPullView(Context context) {
        this(context, null);
    }

    public BottomPullView(Context context, AttributeSet attrs) {
        super(context, attrs);
        DisplayMetrics dm = new DisplayMetrics();
        dm = getResources().getDisplayMetrics();
        float density = dm.density; // 屏幕密度（像素比例：0.75/1.0/1.5/2.0）
        int densityDPI = dm.densityDpi; // 屏幕密度（每寸像素：120/160/240/320）
        float xdpi = dm.xdpi;
        float ydpi = dm.ydpi;
        screenWidth = dm.widthPixels; // 屏幕宽（像素，如：480px）
        screenHeight = dm.heightPixels; // 屏幕高（像素，如：800px）

        this.mContext = context;
        mScroller = new OverScroller(context);
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
        footView = (LinearLayout) LayoutInflater.from(getContext()).inflate(
                R.layout.listview_footer, null);
        refreshStatusTextView = (TextView) footView.findViewById(R.id.refresh_status_textview);
        listviewHheaderProgressbar = (ProgressBar) footView.findViewById(R.id.listview_header_progressbar);
        listviewHeaderArrow = (ImageView) footView.findViewById(R.id.listview_header_arrow);
        tvUpdataTimeTtip = (TextView) footView.findViewById(R.id.updata_time_tip);
        tvLastRefreshTime = (TextView) footView.findViewById(R.id.last_refresh_time);

        footView.setVisibility(GONE);
//        footView.setState(BaseRefreshHeader.STATE_REFRESHING);
        //获取计算圆图案的大小
        final DisplayMetrics metrics = getResources().getDisplayMetrics();
        mFootViewWidth = (int) (360 * metrics.density);
        mFootViewHeight = (int) (60 * metrics.density);

        addView(footView);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        final int action = MotionEventCompat.getActionMasked(ev);
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
                mIsBeingDragged = false;
                final float initialDownY = getMotionEventY(ev, mActivePointerId);
                if (initialDownY == -1) {
                    return false;
                }
                mInitialDownY = initialDownY;
                break;
            case MotionEvent.ACTION_MOVE:
                if (mActivePointerId == INVALID_POINTER) {
                    Log.d("sss", "mActivePointerId==INVALID_POINTER报错");
                    return false;
                }
                final float y = getMotionEventY(ev, mActivePointerId);
                final float yDiff = y - mInitialDownY;
                if (Math.abs(yDiff) > mTouchSlop && !mIsBeingDragged) {
                    mInitialMotionY = mInitialDownY + mTouchSlop;
                    mIsBeingDragged = true;
                    //|| (yDiff < 0 && !mTagerView.canScrollVertically(1))
                    //|| (yDiff > 0 && !mTagerView.canScrollVertically(-1))
                    if ((yDiff < 0 && !mTagerView.canScrollVertically(1))) {
                        return true;
                    } else {
                        mIsBeingDragged = false;
                    }
                }
                break;
            case MotionEvent.ACTION_CANCEL:
                mIsBeingDragged = false;
                break;
        }
        return mIsBeingDragged;
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        final int width = getMeasuredWidth();
        final int height = getMeasuredHeight();


        if (mTagerView == null) {
            ensureTarget();
        }
        if (mTagerView == null) {
            return;
        }

        View child = mTagerView;
        int childLeft = getPaddingLeft();
        int childTop = getPaddingTop();
        int childWidth = width - getPaddingLeft() - getPaddingRight();
        int childHeight = height - getPaddingTop() - getPaddingBottom();
        child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);


        int footerHeight = footView.getHeight() - footView.getPaddingTop() - footView.getPaddingBottom();
        //底部布局大小
//        footView.layout(childLeft, childTop + height, childLeft + childWidth, childTop + height + footerHeight);
        footView.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight + mFootViewHeight);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (mTagerView == null) {
            ensureTarget();
        }
        if (mTagerView == null) {
            return;
        }
        mTagerView.measure(MeasureSpec.makeMeasureSpec(
                getMeasuredWidth() - getPaddingLeft() - getPaddingRight(),
                MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(
                getMeasuredHeight() - getPaddingTop() - getPaddingBottom(), MeasureSpec.EXACTLY));
        footView.measure(MeasureSpec.makeMeasureSpec(mFootViewWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(mFootViewHeight, MeasureSpec.EXACTLY));
    }

    private void ensureTarget() {
        if (mTagerView == null) {
            for (int i = 0; i < getChildCount(); i++) {
                View child = getChildAt(i);
                if (child instanceof RecyclerView) {
                    mTagerView = child;
                    break;
                }
            }
        }
    }

    private boolean isComplete;
    float overscrollTop;

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        final int action = ev.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                mIsBeingDragged = false;
                break;
            case MotionEvent.ACTION_MOVE: {
                if (mActivePointerId == INVALID_POINTER) {
                    return false;
                }
                final float y = getMotionEventY(ev, mActivePointerId);
                //记录手指移动的距离，nInitialMotionY是初始的位置，DRAG_RATE是拖拽因子 默认为0.5
                overscrollTop = (y - mInitialMotionY) * 0.5f;
                if (mIsBeingDragged) {
                    //(overscrollTop > 0 && !canScrollVertically(-1)) ||
                    if ((overscrollTop < 0 && !mTagerView.canScrollVertically(1))) {
                        //赋值给mTarget的top使之能产生拖动的效果
                        mTagerView.setTranslationY(overscrollTop);
                        footView.setTranslationY(overscrollTop);
                        if (Math.abs(overscrollTop) > 300) {
                            isComplete = true;
                        }
                        listviewHheaderProgressbar.setVisibility(INVISIBLE);
                        listviewHeaderArrow.setVisibility(VISIBLE);
                        footView.setVisibility(VISIBLE);
                        if (Math.abs(overscrollTop) > 300) {
                            refreshStatusTextView.setText("释放加载数据");
//                            listviewHeaderArrow.setRotationX(306f);
                            listviewHeaderArrow.setRotation(0f);
                            isLoadData = true;
                        } else if (Math.abs(overscrollTop) <= 300) {
                            refreshStatusTextView.setText("释放取消加载");
                            listviewHeaderArrow.setRotation(180f);
                            isLoadData = false;
                        }
                        //展示刷新时间
                        if (!TextUtils.isEmpty(lastRefreshTimeStr)) {
                            tvUpdataTimeTtip.setVisibility(VISIBLE);
                            tvLastRefreshTime.setText(lastRefreshTimeStr);
                            tvLastRefreshTime.setVisibility(VISIBLE);
                        }
                    } else {
                        return false;
                    }
                }
                break;
            }
            case MotionEvent.ACTION_UP: {
                mIsBeingDragged = false;
                if (isLoadData) {
                    lastRefreshTimeStr = friendlyTime(new Date(lasttime));
                    listviewHeaderArrow.setVisibility(INVISIBLE);
                    listviewHheaderProgressbar.setVisibility(VISIBLE);
                    refreshStatusTextView.setText("正在加载....");
                    listviewHheaderProgressbar.setMax(100);
                    ValueAnimator oba = ValueAnimator.ofFloat(0f, 1f).setDuration(5000);
                    oba.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                        @Override
                        public void onAnimationUpdate(ValueAnimator animation) {
                            float value = (float) animation.getAnimatedValue();
                            listviewHheaderProgressbar.setProgress((int) (value * 100));
                        }
                    });
                    oba.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            //手指松开时候启动动画回到顶部
                            mTagerView.animate().translationY(0).setDuration(200).start();
                            footView.animate().translationY(-overscrollTop).setDuration(200).start();

//                        footView.animate().translationY(200).setDuration(200).start();
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {

                        }
                    });
                    oba.start();
                } else {
                    mTagerView.animate().translationY(0).setDuration(200).start();
                    footView.animate().translationY(200).setDuration(200).start();
                }
//                if (isComplete) {
//                    if (mBottomPullCompleteLister != null) {
//                        mBottomPullCompleteLister.complete();
//                    }
//                    isComplete = false;
//                }
                return false;
            }
            case MotionEvent.ACTION_CANCEL:
                return false;
        }
        return true;
    }

    @Override
    public void computeScroll() {
        if (mScroller.computeScrollOffset()) {
            scrollTo(0, mScroller.getCurrY());
            invalidate();
        }
    }

    public float getMotionEventY(MotionEvent ev, int activePoninterId) {
        final int index = MotionEventCompat.findPointerIndex(ev, activePoninterId);
        if (index < 0) {
            return -1;
        }
        return MotionEventCompat.getY(ev, index);
    }

    public BottomPullCompleteLister mBottomPullCompleteLister;

    public void setBottomPullCompleteLister(BottomPullCompleteLister bottomPullCompleteLister) {
        this.mBottomPullCompleteLister = bottomPullCompleteLister;
    }

    public interface BottomPullCompleteLister {
        void complete();
    }

    public String friendlyTime(Date time) {
        int ct = (int) ((System.currentTimeMillis() - time.getTime()) / 1000);
        lasttime = System.currentTimeMillis();
        if (ct == 0) {
            return mContext.getResources().getString(R.string.text_just);
        }

        if (ct > 0 && ct < 60) {
            return ct + mContext.getResources().getString(R.string.text_seconds_ago);
        }

        if (ct >= 60 && ct < 3600) {
            return Math.max(ct / 60, 1) + mContext.getResources().getString(R.string.text_minute_ago);
        }
        if (ct >= 3600 && ct < 86400)
            return ct / 3600 + mContext.getResources().getString(R.string.text_hour_ago);
        if (ct >= 86400 && ct < 2592000) { //86400 * 30
            int day = ct / 86400;
            return day + getContext().getResources().getString(R.string.text_day_ago);
        }
        if (ct >= 2592000 && ct < 31104000) { //86400 * 30
            return ct / 2592000 + mContext.getResources().getString(R.string.text_month_ago);
        }
        return ct / 31104000 + mContext.getResources().getString(R.string.text_year_ago);
    }
}
